package fluebot;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jibble.pircbot.PircBot;

/**
 *
 * @author Aksel Kvitberg
 */
public class Bash extends PircBot {

	static Random r = new Random();

	public static String getMessage() {
		String returnStr = "";
		BufferedReader in = null;
		try {
			int rand = r.nextInt(20753);
			URL bash = new URL("http://bash.org/?" + rand);
			in = new BufferedReader(new InputStreamReader(bash.openStream()));
			String inputLine;
			while ((inputLine = in.readLine()) != null) {
				returnStr += inputLine;
			}
			in.close();
			String quote = parseBash(returnStr);
			if (quote.isEmpty()){
				quote = getMessage();
				return quote;
			}
			return "#" + rand + ": " + quote;
		} catch (IOException ex) {
			Logger.getLogger(Bash.class.getName()).log(Level.SEVERE, null, ex);
		} finally {
			try {
				in.close();
			} catch (IOException ex) {
				Logger.getLogger(Bash.class.getName()).log(Level.SEVERE, null, ex);
			}
		}
		return null;
	}

	private static String parseBash(String str) {
		Pattern p = Pattern.compile("<p class=\"qt\">(.+?)</p>");
		Matcher m = p.matcher(str);

		if (m.find()) {
			String quote = m.group(1);
			quote = quote.replaceAll("&lt;", "<");
			quote = quote.replaceAll("&gt;", ">");
			quote = quote.replaceAll("&quot;", "\"");
//			quote = quote.replaceAll("<br />", "\r");
			if (quote.contains("<br />"))
				return "";
			else
				return quote;
		}
		return "";
	}
}
